<template>
  <div class="app-container">
    <el-form
      :model="form"
      label-width="68px"
      :inline="true"
      class="demo-form-inline"
    >
      <el-form-item label="课程名称">
        <el-input v-model="form.name" placeholder="请输入课程名称" />
      </el-form-item>
      <el-form-item label="课程类型">
        <el-select v-model="form.type" placeholder="课程类型" clearable>
          <el-option
            v-for="item in typeList"
            :key="item"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用人群">
        <el-select v-model="form.applyTo" placeholder="适用人群" clearable>
          <el-option
            v-for="item in applyList"
            :key="item"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="最低价格">
        <el-input-number
          v-model="form.minPrice"
          :precision="2"
          :step="100"
          placeholder="适用人群"
        />
      </el-form-item>
      <el-form-item label="最高价格">
        <el-input-number
          v-model="form.maxPrice"
          :precision="2"
          :step="100"
          placeholder="适用人群"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="SearchFun"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetFun">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="el-row mb8" style="margin-left: -5px; margin-right: -5px">
      <div
        class="el-col el-col-1.5 is-guttered"
        style="padding-left: 5px; padding-right: 5px"
      >
        <el-button type="primary" plain icon="Plus" @click="addFun"
          >新增</el-button
        >
      </div>
      <div
        class="el-col el-col-1.5 is-guttered"
        style="padding-left: 5px; padding-right: 5px"
      >
        <el-button type="success" plain icon="Edit"
          :disabled="multipleSelection.length !== 1"
          @click="handleEditBtn"
        >修改</el-button>
      </div>
      <div
        class="el-col el-col-1.5 is-guttered"
        style="padding-left: 5px; padding-right: 5px"
      >
        <el-button type="danger" plain icon="Delete"
          :disabled="multipleSelection.length === 0"
          @click="handleBatchDelete"
        >删除</el-button>
      </div>
      <div
        class="el-col el-col-1.5 is-guttered"
        style="padding-left: 5px; padding-right: 5px"
      >
        <el-button type="warning" plain icon="Download" @click="exportExcel">导出</el-button>
      </div>
      <div class="top-right-btn">
        <div class="el-row">
          <el-button icon="Search" circle />
          <el-button icon="Refresh" circle @click="resetFun" />
        </div>
      </div>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" class-name="is-center" />
        <el-table-column label="课程编号" class-name="is-center" width="78px">
          <template #default="scope">{{ scope.row.courseId }}</template>
        </el-table-column>
        <el-table-column label="课程类型" class-name="is-center" width="120px">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 1" type="primary">舞蹈类</el-tag>
            <el-tag v-if="scope.row.type == 2" type="success">游泳类</el-tag>
            <el-tag v-if="scope.row.type == 3" type="info">拳击类</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          property="name"
          label="课程名称"
          show-overflow-tooltip
          width="120px"
          class-name="is-center"
        />
        <el-table-column
          property="price"
          label="课程价格"
          width="120px"
          class-name="is-center"
        />
        <el-table-column label="课程适用人群" class-name="is-center">
          <template #default="scope">
            <el-tag v-if="scope.row.applyTo == 1" type="primary"
              >中小学生</el-tag
            >
            <el-tag v-if="scope.row.applyTo == 2" type="success">上班族</el-tag>
            <el-tag v-if="scope.row.applyTo == 3" type="info">小白用户</el-tag>
            <el-tag v-if="scope.row.applyTo == 4" type="warning"
              >健身达人</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          property="info"
          label="课程简介"
          width="178px"
          class-name="is-center"
        />
        <el-table-column label="创建时间" class-name="is-center">
          <template #default="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" class-name="is-center">
          <template #default="scope">
            <el-button
              @click="handleEdit(scope.$index, scope.row)"
              icon="Edit"
              type="primary"
              link
            >
              修改
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDelete(scope.row)"
              icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="form.pageNum"
          v-model:page-size="form.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model:model-value="dialogVisible"
      @update:model-value="val => dialogVisible = val"
      title="添加课程"
      width="500"
      :before-close="() => { dialogVisible = false }"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="课程分类" prop="type">
              <el-select v-model="ruleForm.type" placeholder="课程分类">
                <el-option v-for="item in typeList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="适用人群" prop="applyTo">
              <el-select v-model="ruleForm.applyTo" placeholder="课程适用人群">
                <el-option v-for="item in applyList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程价格" prop="price">
              <el-input-number v-model="ruleForm.price" :precision="2" :step="100" placeholder="课程价格" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="课程简介" prop="info">
          <el-input v-model="ruleForm.info" type="textarea" placeholder="请输入课程简介" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import {
  getCourseList,
  getTypeList,
  getApplyList,
  delCourse,
  addCourse,
  updateCourse,
} from "../../../api/course";
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from 'xlsx';

const total = ref(1);
// const currentPage4 = ref(1);
// const pageSize4 = ref(10);
const size = ref<'default' | 'small' | 'large'>("default");
const background = ref(true);
const disabled = ref(false);
const typeList = ref<any[]>([]);
const applyList = ref<any[]>([]);

const handleSizeChange = (val: number) => {
  form.pageSize = val;
  getCourse();
};
const handleCurrentChange = (val: number) => {
  form.pageNum = val;
  getCourse();
};

const tableData = ref<any[]>([]);
const form = reactive({
  name: "",
  type: "",
  applyTo: "",
  minPrice: undefined,
  maxPrice: undefined,
  pageNum: 1,
  pageSize: 10,
});

const getCourse = async () => {
  const res: any = await getCourseList(form);
  //   console.log(res);
  if (res.code == 200) {
    tableData.value = res.rows;
    total.value = res.total;
  }
};
getCourse();

// 课程类型列表
const getType = async () => {
  const res: any = await getTypeList();
  if (res.code == 200) {
    typeList.value = res.data;
  }
};
getType();

// 适用人群列表
const applyType = async () => {
  const res: any = await getApplyList();
  if (res.code == 200) {
    applyList.value = res.data;
  }
};
applyType();

const SearchFun = () => {
  getCourse();
};

const resetFun = () => {
  form.name = "";
  form.type = "";
  form.applyTo = "";
  form.minPrice = undefined;
  form.maxPrice = undefined;

  // 2. 重置分页参数
  form.pageNum = 1;
  form.pageSize = 10;

  // 3. 重新加载数据
  getCourse();
};

// 删除方法
const handleDelete = (item) => {
  ElMessageBox.confirm("是否确认删除课程编号为'481'的数据项？", "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await delCourse(item.courseId);
      ElMessage.success("删除成功");
      getCourse();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

const dialogVisible = ref(false);

// 新增课程表单
const ruleFormRef = ref();
const ruleForm = reactive({
  name: '',
  type: '',
  applyTo: '',
  price: undefined,
  info: '',
});

const rules = {
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择课程类型', trigger: 'change' },
  ],
  applyTo: [
    { required: true, message: '请选择适用人群', trigger: 'change' },
  ],
  price: [
    { required: true, message: '请输入课程价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' },
  ],
  info: [
    { required: true, message: '请输入课程简介', trigger: 'blur' },
  ],
};

const isEdit = ref(false);
const currentEditId = ref(null);
const addFun = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  currentEditId.value = null;
  Object.assign(ruleForm, { name: '', type: '', applyTo: '', price: undefined, info: '' });
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateCourse({ ...ruleForm, courseId: currentEditId.value });
          ElMessage.success('修改课程成功');
        } else {
          await addCourse(ruleForm);
          ElMessage.success('新增课程成功');
        }
        dialogVisible.value = false;
        getCourse();
      } catch (error) {
        ElMessage.error(isEdit.value ? '修改课程失败' : '新增课程失败');
      }
    }
  });
};

const handleEdit = (index, row) => {
  dialogVisible.value = true;
  isEdit.value = true;
  currentEditId.value = row.courseId;
  Object.assign(ruleForm, {
    name: row.name,
    type: row.type,
    applyTo: row.applyTo,
    price: row.price,
    info: row.info,
  });
};

const multipleSelection = ref<any[]>([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleEditBtn = () => {
  if (multipleSelection.value.length === 1) {
    handleEdit(0, multipleSelection.value[0]);
  }
};

const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) return;
  ElMessageBox.confirm(
    `是否确认删除选中的${multipleSelection.value.length}条课程？`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      // 支持批量删除API时可直接传id数组，否则循环删除
      for (const item of multipleSelection.value) {
        await delCourse(item.courseId);
      }
      ElMessage.success('删除成功');
      getCourse();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const exportExcel = () => {
  // 只导出表格展示的主要字段
  const data = tableData.value.map(row => ({
    课程编号: row.courseId,
    课程名称: row.name,
    课程类型: (typeList.value.find(t => t.dictValue == row.type)?.dictLabel) || row.type,
    课程价格: row.price,
    适用人群: (applyList.value.find(a => a.dictValue == row.applyTo)?.dictLabel) || row.applyTo,
    课程简介: row.info,
    创建时间: row.createTime
  }));
  const ws = XLSX.utils.json_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '课程列表');
  XLSX.writeFile(wb, '课程列表.xlsx');
};
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
